class: hide-logo, middle background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Plotly_logo_for_digital_final_%286%29.png/1600px-Plotly_logo_for_digital_final_%286%29.png) background-position: right background-size: 50% 50% # .center[**Interactive Plotting with plotly in R**] -------------------------------------- ## Steve Kerr & Julian Kath ## Hertie School ## 2021-10-30 --- # Overview .pull-left[.font160[ <br> </br> 1. What is plotly? 1. Why plotly? 1. How does plotly work? 1. What can plotly do? 1. Conclusion 1. Resources 1. Let's Practice! ]] .pull-right[ </br> </br> </br> </br> </br>  ] --- class: hide-logo, inverse, center, middle # **What is plotly?** --- background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Plotly_logo_for_digital_final_%286%29.png/1600px-Plotly_logo_for_digital_final_%286%29.png) background-position: bottom background-size: 75% 75% # What is plotly? .font150[ plotly is an R package for creating **interactive** and **dynamic** **web-based** graphics 1. Audiences can directly **interact** with your data 1. **Dynamic** graphics change automatically 1. **Web-based** graphics can be easily shared ] --- # Types of Graphics <details> <summary> Static </summary> .details[.center[ <!-- --> ]] </details> <details> <summary> Interactive </summary> .details[.center[ <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ]] </details> <details> <summary> Dynamic </summary> .details[.center[ <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ]] </details> --- # Types of Graphics .center2[  ] --- class: hide-logo, inverse, center, middle # **Why plotly?** --- # Why plotly? <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ??? Parameters don't work with plotly --- # Why plotly? .font200[ Strengths of interactive Plotting: - Complex Information - High-dimensional data - Exploratory data analysis - Engaging viewer experience ] --- class: hide-logo, inverse, center, middle # **How does plotly work?** --- # How does plotly work? <br></br> <br></br> .font180[ ## 1. Transform **ggplot** graphics into **plotly** graphics with **ggplotly()** ] -- <br></br> <br></br> .font180[ ## 2. Initialize **plotly** graphics directly with **plot_ly()** ] --- # #1 ggplot →️ plotly <details> <summary> Code </summary> .details[ ```r library(ggplot2) library(babynames) gg <- babynames %>% filter(name %in% c("Sam", "Alex")) %>% ggplot() + geom_line(aes(year, prop, color = sex, linetype = name)) * p_gg <- ggplotly(gg, dynamicTicks = TRUE) %>% rangeslider() %>% layout(hovermode = "x") ``` ] </details> <details> <summary> ggplot </summary> .details[ <!-- --> ] </details> <details> <summary> ggplotly </summary> .details[ <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ] </details> --- # #2 plotly <details> <summary> Code </summary> .details[.code120[ ```r p <- babynames %>% filter(name %in% c("Sam", "Alex")) %>% plot_ly(x = ~year, y = ~prop, color = ~sex, linetype = ~name, dynamicTicks = TRUE, hoverinfo = "text", text = ~paste0( "<br>", name, " ", sex, "<br>Probability: ", round(prop, 5), "<br>Year: ", year, "<br>" )) %>% add_lines() %>% rangeslider() %>% layout(xaxis = list(title = "Year"), yaxis = list(title = "Probability"), hovermode = "x", paper_bgcolor = 'rgba(0,0,0,0)', plot_bgcolor = 'rgba(0,0,0,0)') ``` ]] </details> <details> <summary> Plot </summary> .details[.code120[ <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ]] </details> --- # Grammar of Graphics .font170[ - Key Terms + **Trace**: the data + **Trace Type**: ex. histogram, pie, scatter, etc. + **Attribute**: the style - Call plotly with **plot_ly** and map variables - Chain traces with pipes **%>%** - Always pass variables with a tilde **~** - You will oftentimes need to pass parameters in **lists**!] --- class: hide-logo, inverse, center, middle # **What else can plotly do?** --- # Subplots <details> <summary> Code </summary> .details[ ```r > library(plotly) > > # read in Walmart data > df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/1962_2006_walmart_store_openings.csv") > > # first plot - bar chart > total <- plyr::count(df$YEAR) > fit <- fitted(loess(total$freq ~ total$x)) > fig1 <- plot_ly(data = total, x = ~x, y = ~freq, type = "bar", showlegend=FALSE, + marker=list(color = ~x, showscale=FALSE)) %>% + add_lines(y = fit, showlegend=FALSE, color = 'black') %>% + layout(showlegend=FALSE, xaxis = list(side = "right", showgrid = FALSE), + yaxis = list(showgrid=FALSE), paper_bgcolor = 'rgba(0,0,0,0)', plot_bgcolor = 'rgba(0,0,0,0)') > > # second plot - scattergeo map > g <- list( + scope = 'usa', + projection = list(type = 'albers usa'), + showlakes = FALSE, + showocean = TRUE, + oceancolor = 'rgba(0,0,0,0)') > > fig2 <- plot_geo(df, lat = ~LAT, lon = ~LON) %>% + add_markers(text = ~OPENDATE, showlegend=FALSE, marker=list(color = ~YEAR, showscale=FALSE), hoverinfo = "text") %>% + layout(geo = g, showlegend=FALSE, paper_bgcolor = 'rgba(0,0,0,0)', plot_bgcolor = 'rgba(0,0,0,0)', width = 800) > > # subplot *> fig <- subplot(fig1, fig2, nrows = 2) %>% + layout(title = "Walmart Store Openings by Year", + xaxis = list(domain=list(x=c(0,0.5),y=c(0,0.5))), + scene = list(domain=list(x=c(0.5,1),y=c(0,0.5))), + xaxis2 = list(domain=list(x=c(0.5,1),y=c(0.5,1))), + showlegend=FALSE,showlegend2=FALSE, paper_bgcolor = 'rgba(0,0,0,0)', + plot_bgcolor = 'rgba(0,0,0,0)', width = 800) ``` ] </details> <details> <summary> Plot </summary> <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b </details> --- # Animated Plots <details> <summary> Code </summary> .details.code90[ ```r > library(plotly) > library(gapminder) # dataset > library(tidyverse) > > gapminder %>% + plot_ly(x = ~gdpPercap, y = ~lifeExp, # variables + hoverinfo = "text", + text = ~paste("</br> Country: ", country, # Hover text box + "</br> GDP per capita: ", round(gdpPercap, 0), + "</br> Life Expectancy: ", lifeExp, + "</br> Population: ", round(pop/1000000, 0), " Mio")) %>% + add_text(x = 6500, y = 40, # Background text + text = ~year, frame = ~year, + textfont = list(size = 150, + color = toRGB("gray80"))) %>% + add_markers(size = ~pop, color = ~continent, # Customizing Markers, Mapping continent onto color + frame = ~year, ids = ~country, + marker = list(sizemode = "diameter")) %>% + layout(title = "GDP per capita vs. Life Expectancy from 1952 to 2007", + xaxis = list(type = "log", + title = "GDP per capita"), + yaxis = list(type = "log", + title = "Life Expectancy at birth"), + paper_bgcolor = 'rgba(0,0,0,0)', # Transparent Background Color + plot_bgcolor = 'rgba(0,0,0,0)', + showlegend = FALSE, + autosize = F, width = 850, height = 500) %>% # adjust size *+ animation_opts(frame = "500", # Setting animation options. *+ transition = "500", *+ easing = "linear", *+ redraw = TRUE) %>% *+ animation_slider(hide = TRUE) -> ani_plot ``` ] </details> <details> <summary> Plot </summary> </br> .details[ <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ] </details> --- # Linked Plots <details> <summary> Code </summary> .details[.code70[ ```r *> library(crosstalk) > library(openintro) # dataset > library(plotly) > *> shared_data <- SharedData$new(cia_factbook, *+ key = ~country) > # This creates a shared dataframe for both plots > > p1 <- shared_data %>% # First Subplot + plot_ly(x = ~population, # X-axis vector + y = ~internet_users, # Y-axis vector + hoverinfo = "text", + text = ~paste0("</br> ", country, + "</br> Population: ", round(population/1000, 0), "k", + "</br> Internet Users: ", round(internet_users/1000, 0), "k" + ) + ) %>% # Editing the hover info + add_markers() %>% + layout(xaxis = list(type = "log", title = "Population"), + yaxis = list(type = "log", title = "Internet Users"), # Plot Labels, Axis scaling + paper_bgcolor = 'rgba(0,0,0,0)', + plot_bgcolor = 'rgba(0,0,0,0)') > > p2 <- shared_data %>% # Second Subplot + plot_ly(x = ~population_growth_rate, + y = ~net_migration_rate, + hoverinfo = "text", + text = ~paste0("</br> ", country, + "</br> Population Growth: ", population_growth_rate, + "</br> Net Migration: ", net_migration_rate)) %>% + layout(xaxis = list(type = "log", title = "Population Growth Rate"), + yaxis = list(type = "log", title = "Net Migration Rate"), + paper_bgcolor = 'rgba(0,0,0,0)', + plot_bgcolor = 'rgba(0,0,0,0)') > *> subplot(p1, p2, titleX = TRUE, titleY = TRUE) %>% + hide_legend() %>% + layout(title = "Linked Graphs in plotly", + width = 800) %>% *+ highlight(on = "plotly_selected") -> linked_plot ``` ]] </details> <details> <summary> Plot </summary> .details[ <<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b ] </details> --- # Filters <details> <summary> Code </summary> .details[ ```r > library(crosstalk) > > diamonds %>% + SharedData$new() -> shared_data # create shared data frame object > shared_data %>% + plot_ly(x = ~carat, y = ~price, color = ~clarity) %>% # Mapping Variables + layout( + xaxis = list(title = "Carat"), yaxis = list(title = "Price"), + paper_bgcolor = 'rgba(0,0,0,0)', plot_bgcolor = 'rgba(0,0,0,0)', + updatemenus = list( # Creating plotly native buttons for changing plot type + list(y = 0.35, x = 1, label = "Plot Type", *+ buttons = list( + list(method = "restyle", + args = list("type", "scatter"), # Scatter as first option + label = "Scatter Plot"), + list(method = "restyle", + args = list("type", "histogram2d"), # 2D Histogram as second option + label = "2D Histogram"))))) -> filter_plot > *> bscols(widths = c(2,7), + list(filter_checkbox(id = "quality_checks", # Checkboxes for cut quality + label = "Cut Quality", + sharedData = shared_data, + group = ~cut), + filter_select(id = "clarity_search", # Select-Search bar for Clarity level + label = "Select Clarity Level", + sharedData = shared_data, + group = ~clarity), + filter_slider(id = "depth_slider", # Slider option for depth variable + label = "Depth", + sharedData = shared_data, + column = ~depth)), # Pay attention! The slider filters a column! + filter_plot) -> filter_plot ``` ] </details> <details> <summary> Plot </summary> .details[
Cut Quality
Fair
Good
Very Good
Premium
Ideal
Select Clarity Level
Depth
<<<<<<< HEAD
=======
>>>>>>> 60621964d770a615c5f9520303ecc59c96188a6b
] </details> --- class: hide-logo, inverse, center, middle # **Conclusion** --- # Conclusion .font160[ - plotly is an R package for creating **interactive** and **dynamic** **web-based** graphics <br></br> - plotly graphics can be created by (1) **converting ggplot()** graphics and (2) initializing **directly with plot_ly()** <br></br> - Key features include the ability to create **subplots**, **animate** graphs, **link** plots, and **filter** observations to enable the audience to interact with your data <br></br> - plotly might **not always** be the right tool! ] --- # Resources .font200[ - [Getting Started with plotly in R](https://plotly.com/r/getting-started/) <br></br> - [Interactive web-based data visualization with R, plotly, and shiny](https://plotly-r.com/) <br></br> - [Getting Started with plotly in ggplot2](https://plotly.com/ggplot2/getting-started/) <br></br> - [plotly Cheat Sheet](https://images.plot.ly/plotly-documentation/images/r_cheat_sheet.pdf) ] --- # References .font200[ - [Intro to Animations](https://plotly.com/r/animations/) <br></br> - [R for Data Science, Ch. 3 Data Visualisation](https://r4ds.had.co.nz/data-visualisation.html) <br></br> - [Mixed Subplots](https://plotly.com/r/mixed-subplots/) <br></br> - [Interactive Charts](https://www.r-graph-gallery.com/interactive-charts.html) ] --- class: hide-logo, inverse, center, middle # **Let's practice!**